package com.wu.ssm.spring.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 创建对象的三种方法 Foo foo1 = new Foo();还有反射两种如下所示
 * Created by wzf on 2018/11/26/026.
 */
public class ReflectionUtil {

    private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 根据类类型反射获得实例
     */
    public static Object newInstance(Class<?> clazz){
        Object instance;
        try {
            instance = clazz.newInstance();
        } catch (Exception e) {
            throw new  RuntimeException();
        }
        return instance;
    }

    /**
     * 根据类全名反射获得实例
     */
    /*public static Object newInstance(String className){
        Class<?> cls = ClassUtil.loadClass(className);
        return newInstance(cls);
    }*/

    /**
     * 通过反射创建实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T newInstance(String className) {
        T instance;
        try {
            Class<?> commandClass = ClassUtil.loadClass(className);
            instance = (T) commandClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return instance;
    }

    public static Object invokeMethod(Object obj, Method method, Object...args){
        Object result;
        method.setAccessible(true);
        try {
            result = method.invoke(obj, args);
        } catch (Exception e) {
            LOGGER.error("反射调用方法失败");
            throw new RuntimeException(e);
        }
        return result;
    }

    public static void setFeild(Object obj, Field field, Object value){
        field.setAccessible(true);
        try {
            field.set(obj, value);
        } catch (Exception e) {
            LOGGER.error("反射设置成员变量失败");
            throw new RuntimeException(e);
        }

    }

}
